from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenRefreshSerializer
from .models import UserDevice
from django.contrib.auth import authenticate


class UserDeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserDevice
        fields = [
            'id',
            'device_id',
            'device_name',
            'device_type',
            'browser',
            'os',
            'ip_address',
            'last_login',
            'is_active',
            'created_at',
            'updated_at'
        ]
        read_only_fields = [
            'id',
            'device_id',
            'device_name',
            'device_type',
            'browser',
            'os',
            'ip_address',
            'last_login',
            'created_at',
            'updated_at'
        ]

class EmptySerializer(serializers.Serializer):
    pass

class TokenResponseSerializer(serializers.Serializer):
    access = serializers.CharField(help_text='访问令牌')
    refresh = serializers.CharField(help_text='刷新令牌')
    device_id = serializers.CharField(help_text='设备标识符')

class TokenObtainRequestSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate(self, attrs):
        self.user = authenticate(
            username=attrs.get('username'),
            password=attrs.get('password')
        )
        
        if not self.user:
            raise serializers.ValidationError({
                'detail': '未找到匹配的活跃账户'
            })
            
        # 检查用户是否是 staff
        if not self.user.is_staff:
            raise serializers.ValidationError({
                'detail': '只有工作人员可以登录系统'
            })
        
        return attrs

class TokenRefreshRequestSerializer(TokenRefreshSerializer):
    refresh = serializers.CharField(required=True, help_text='刷新令牌')

class TokenRefreshResponseSerializer(serializers.Serializer):
    access = serializers.CharField(help_text='新访问令牌')
    refresh = serializers.CharField(help_text='刷新令牌')

class DeviceLogoutSerializer(serializers.Serializer):
    device_id = serializers.CharField(required=True, help_text='设备唯一标识')

class UserIdQuerySerializer(serializers.Serializer):
    user_id = serializers.IntegerField(required=True, help_text='用户ID')

